package query_understanding.query_understand.tree_selector;

import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.stereotype.Component;
import query_understanding.query_language.doc_entity_tree.DocumentQueryTree;
import query_understanding.query_language.doc_entity_tree.EntityQueryTree;
import query_understanding.query_understand.tree_generator.QueryTreeGenerator;
import query_understanding.query_understand.tree_progress.DocumentQueryProgress;
import query_understanding.query_understand.tree_progress.EntityQueryProgress;

import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;

/**
 * Created by julianzliu on 4/22/2017.
 */

@Component
public class QueryTreeSelector {

    private QueryTreeGenerator generator;


    public QueryTreeSelector(){
        this.generator = new QueryTreeGenerator();
    }


    public DocumentQueryProgress genDocQueryTree(String query){
        DocumentQueryProgress progress = this.generator.parseQuery( query  );

        List<EntityQueryTree>  entityQueryTreeList = new ArrayList<>();

        for(EntityQueryProgress entityQueryProgress: progress.entityQueryProgressList){
            EntityQueryTree bestTree = selectFinalEntityTree(entityQueryProgress);
            if(bestTree != null)
                entityQueryTreeList.add(bestTree);
        }

        DocumentQueryTree documentQueryTree = new DocumentQueryTree();
        documentQueryTree.entityQueryTreeList = entityQueryTreeList;

        progress.documentQueryTree =  documentQueryTree;

        return progress;
    }


    private EntityQueryTree selectFinalEntityTree(EntityQueryProgress entityQueryProgress){
        EntityQueryTree tree = null;
        /*
        先查看已经生成的树，在看没有完全生成的树
         */
        PriorityQueue<EntityQueryTree> entityQueryTrees =  entityQueryProgress.finishedPriorityQueue;

        if(entityQueryTrees.size() > 0){
           tree = entityQueryTrees.peek();
        }
        else if(entityQueryProgress.treePriorityQueue.size() > 0){
            tree = entityQueryProgress.treePriorityQueue.peek();
        }

        if(tree != null){
            tree.markAnswerNode();

            tree.query = entityQueryProgress.originalQuery;

            tree.finished = tree.generateFinished();
        }

        return tree;
    }


    /*********************************************************
     *
     * @param args
     */
    public static void main(String[] args){
        String query = "wife of Obama.";
        if(args.length > 0){
            query = "";
            for(String arg : args) query += " " + arg;
        }
        QueryTreeSelector selector  = new QueryTreeSelector();
        DocumentQueryProgress progress = selector.genDocQueryTree( query );
        ObjectNode json = (ObjectNode)( progress.genDocumentTreeJson() );
        System.out.println( json );
    }


}
